<template>
  <Head title="我的订单" />
  <ShopLayout>
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <h1 class="text-3xl font-light text-gray-900 mb-8">我的订单</h1>

        <!-- 筛选和搜索 -->
        <div class="bg-white rounded-2xl p-8 shadow-sm mb-6">
          <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-light text-gray-900">筛选条件</h3>
            <button 
              @click="clearFilters"
              class="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-xl hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
            >
              <svg class="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              重置筛选
            </button>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 状态筛选 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-3">订单状态</label>
              <div class="flex flex-wrap gap-2">
                <button
                  @click="updateFilter('status', '')"
                  :class="[
                    'px-4 py-2 rounded-2xl text-sm font-medium transition-colors',
                    !currentFilters.status ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  ]"
                >
                  全部
                </button>
                <button
                  v-for="status in statusOptions"
                  :key="status.value"
                  @click="updateFilter('status', status.value)"
                  :class="[
                    'px-4 py-2 rounded-2xl text-sm font-medium transition-colors',
                    currentFilters.status === status.value ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  ]"
                >
                  {{ status.label }}
                </button>
              </div>
            </div>
            
            <!-- 搜索 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-3">搜索订单</label>
              <div class="relative">
                <input
                  v-model="searchKeyword"
                  @keyup.enter="updateFilter('keyword', searchKeyword)"
                  type="text"
                  placeholder="订单号/商品名称"
                  class="w-full px-4 py-3 pl-10 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                />
                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                  <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
                <button
                  @click="updateFilter('keyword', searchKeyword)"
                  class="absolute right-2 top-1/2 -translate-y-1/2 px-4 py-2 bg-gray-900 text-white rounded-xl text-sm hover:bg-gray-800 transition-colors"
                >
                  搜索
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单列表 -->
        <div v-if="orders.data.length === 0" class="bg-white rounded-2xl p-12 text-center">
          <p class="text-gray-500 mb-4">暂无订单</p>
          <Link :href="route('home')" class="inline-block px-6 py-3 bg-gray-900 text-white rounded-2xl hover:bg-gray-800 transition-colors">
            去购物
          </Link>
        </div>

        <div v-else class="space-y-6">
          <div
            v-for="order in orders.data"
            :key="order.id"
            class="bg-white rounded-2xl p-8 shadow-sm hover:shadow-md transition-shadow"
          >
            <!-- 订单头部 -->
            <div class="flex items-center justify-between pb-6 border-b border-gray-100 mb-6">
              <div class="flex items-center gap-8">
                <div>
                  <p class="text-sm text-gray-500 mb-1">订单号</p>
                  <p class="text-lg font-light text-gray-900">{{ order.order_number }}</p>
                </div>
                <div>
                  <p class="text-sm text-gray-500 mb-1">下单时间</p>
                  <p class="text-lg font-light text-gray-900">{{ formatDate(order.created_at) }}</p>
                </div>
                <div>
                  <p class="text-sm text-gray-500 mb-1">订单状态</p>
                  <span
                    class="inline-flex items-center px-4 py-2 rounded-2xl text-sm font-medium"
                    :class="getStatusClass(order.status)"
                  >
                    {{ getStatusText(order.status) }}
                  </span>
                </div>
              </div>
              <div class="text-right">
                <p class="text-sm text-gray-500 mb-1">订单金额</p>
                <p class="text-2xl font-light text-gray-900">¥{{ order.total_amount.toLocaleString() }}</p>
                <div v-if="order.user_coupon" class="mt-2">
                  <p class="text-xs text-gray-500">优惠券：{{ order.user_coupon.coupon.name }}</p>
                  <p class="text-xs text-red-500">-¥{{ (order.user_coupon.discount_amount || 0).toLocaleString() }}</p>
                </div>
              </div>
            </div>

            <!-- 订单商品 -->
            <div class="space-y-4">
              <div
                v-for="item in order.items"
                :key="item.id"
                class="flex gap-4 p-4 bg-gray-50 rounded-2xl"
              >
                <img :src="item.product_image || '/images/placeholder.jpg'" :alt="item.product_name" class="w-20 h-20 object-cover rounded-2xl" />
                <div class="flex-1">
                  <p class="text-lg font-medium text-gray-900">{{ item.product_name }}</p>
                  <p v-if="item.product_specs && item.product_specs.length > 0" class="text-sm text-gray-500 mt-1">
                    {{ item.product_specs.map(s => s.value).join(' / ') }}
                  </p>
                  <div class="flex items-center justify-between mt-3">
                    <span class="text-sm text-gray-600">数量：{{ item.quantity }}</span>
                    <span class="text-lg font-medium text-gray-900">¥{{ (item.price || 0).toLocaleString() }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="flex items-center justify-end gap-4 mt-6 pt-6 border-t border-gray-100">
              <Link
                :href="route('order.show', order.order_number)"
                class="px-6 py-3 border border-gray-300 rounded-2xl text-gray-700 hover:bg-gray-50 transition-colors"
              >
                查看详情
              </Link>
              <button
                v-if="canCancel(order)"
                @click="confirmCancel(order)"
                class="px-6 py-3 border border-red-300 rounded-2xl text-red-600 hover:bg-red-50 transition-colors"
              >
                取消订单
              </button>
              <button
                v-if="canConfirmDelivery(order)"
                @click="confirmDelivery(order)"
                class="px-6 py-3 bg-gray-900 text-white rounded-2xl hover:bg-gray-800 transition-colors"
              >
                确认收货
              </button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="orders.last_page > 1" class="mt-8 flex justify-center">
          <nav class="flex items-center gap-2">
            <Link
              v-for="link in orders.links"
              :key="link.label"
              :href="link.url"
              v-html="link.label"
              class="px-4 py-2 rounded-lg transition-colors"
              :class="link.active ? 'bg-gray-900 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'"
            />
          </nav>
        </div>
      </div>
    </div>

    <!-- 取消订单确认 -->
    <ConfirmDialog
      :show="showCancelDialog"
      type="danger"
      title="确认取消订单"
      :message="`确定要取消订单「${orderToCancel?.order_number}」吗？取消后库存将恢复。`"
      confirm-text="取消订单"
      cancel-text="返回"
      @close="showCancelDialog = false; orderToCancel = null"
      @confirm="handleCancelOrder"
    />
  </ShopLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  orders: { type: Object, required: true },
  filters: { 
    type: Object, 
    default: () => ({ status: '', keyword: '' }) 
  }
})

const { showSuccess, showError } = useNotification()

// 筛选和搜索
const currentFilters = computed(() => props.filters || { status: '', keyword: '' })
const searchKeyword = ref(currentFilters.value.keyword || '')

const statusOptions = [
  { label: '待支付', value: 'pending' },
  { label: '待发货', value: 'processing' },
  { label: '已发货', value: 'shipped' },
  { label: '已送达', value: 'delivered' },
  { label: '已取消', value: 'cancelled' }
]

const updateFilter = (key, value) => {
  const newFilters = { ...currentFilters.value, [key]: value }
  
  // 清空空值
  Object.keys(newFilters).forEach(k => {
    if (!newFilters[k]) delete newFilters[k]
  })
  
  router.get(route('orders.index'), newFilters, {
    preserveScroll: false, // 切换筛选时滚动到顶部
    replace: true
  })
}

const clearFilters = () => {
  searchKeyword.value = ''
  router.get(route('orders.index'), {}, {
    preserveScroll: false,
    replace: true
  })
}

// 取消订单
const showCancelDialog = ref(false)
const orderToCancel = ref(null)

const confirmCancel = (order) => {
  orderToCancel.value = order
  showCancelDialog.value = true
}

const handleCancelOrder = () => {
  if (!orderToCancel.value) return

  router.post(route('order.cancel', orderToCancel.value.order_number), {
    reason: '用户取消'
  }, {
    preserveScroll: true,
    onSuccess: () => {
      showSuccess('订单已取消', '')
      showCancelDialog.value = false
      orderToCancel.value = null
    },
    onError: () => {
      showError('取消订单失败', '请重试')
    }
  })
}

// 确认收货
const confirmDelivery = (order) => {
  router.post(route('order.confirm-delivery', order.order_number), {}, {
    preserveScroll: true,
    onSuccess: () => {
      showSuccess('已确认收货', '')
    },
    onError: () => {
      showError('确认收货失败', '请重试')
    }
  })
}

// 判断是否可以取消
const canCancel = (order) => {
  return ['pending', 'processing'].includes(order.status)
}

// 判断是否可以确认收货
const canConfirmDelivery = (order) => {
  return order.status === 'shipped'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'processing': '待发货',
    'shipped': '已发货',
    'delivered': '已送达',
    'cancelled': '已取消'
  }
  return map[status] || status
}

// 获取状态样式
const getStatusClass = (status) => {
  const map = {
    'pending': 'bg-yellow-100 text-yellow-800',
    'processing': 'bg-blue-100 text-blue-800',
    'shipped': 'bg-purple-100 text-purple-800',
    'delivered': 'bg-green-100 text-green-800',
    'cancelled': 'bg-gray-100 text-gray-800'
  }
  return map[status] || 'bg-gray-100 text-gray-800'
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

